import path from 'path';
import fs from 'fs';
import cfg from './config';
import { send } from './help';
import { spawn } from 'child_process';

const onEvent = (...args) => send('bookInstall', ...args);

let bookData;
let bookMd5s = {};
const taskId = `${new Date().getTime()}`;
const name = 'PepReader';
const exeDir = path.join(cfg.dirs.appPath, name);
const exePath = path.join(exeDir, `${name}.exe`);
const bookDataFile = () => path.join(exeDir, 'data.json');

const getBookData = () => {
  try {
    if (!bookData) {
      bookData = JSON.parse(fs.readFileSync(bookDataFile()));
    }
    const res = {};
    for (const key of Object.keys(bookData)) {
      const bookInfo = bookData[key];
      if (bookInfo && bookInfo.status) {
        res[key] = bookInfo;
      }
    }
    return res;
  } catch (error) {
    //
  }
  return bookData;
};

const saveBookData = (bookId, data) => {
  try {
    if (!bookData) {
      bookData = {};
    }
    if (data === null) {
      delete bookData[bookId];
    } else {
      bookData[bookId] = { ...bookData[bookId], ...data };
    }
    fs.writeFileSync(bookDataFile(), JSON.stringify(bookData));
  } catch (error) {
    //
    console.log(error);
  }
};

/**
 * 列表
 */
const bookList = () => Promise.resolve(getBookData());
/**
 * 安装
 * @param {*} param0
 * @param {*} dirInfo
 */
const bookInstall = async ({ userId, bookId, bookMd5, bookExe, downType }) => {
  if (!bookMd5s || !bookMd5s[bookId]) {
    bookMd5s[bookId] = bookMd5;
  }
  const args = `${taskId} bookInstall ${userId} ${bookId} ${downType}`;
  return pepReaderOps({ args, userId, bookId, bookMd5, bookExe });
};

/**
 * 打开
 * @param {*} param0
 */
const bookOpen = ({ userId, bookId }) => {
  return new Promise((resole) => {
    const args = `${taskId} bookOpen ${userId} ${bookId}`;
    pepReaderOps({ args, userId, bookId });
    resole();
  });
};

/**
 * 获取教材章节目录
 * @param {*} param0
 * @returns
 */
const bookChaptersGet = async ({ userId, bookId }) => {
  const args = `${taskId} chaptersGet ${userId} ${bookId}`;
  return pepReaderOps({ args, userId, bookId });
};

/**
 * 卸载
 * @param {*} param0
 */
const bookUninstall = async ({ userId, bookId }) => {
  if (bookMd5s && bookMd5s[bookId]) {
    delete bookMd5s[bookId];
  }
  const args = `${taskId} bookUninstall ${userId} ${bookId}`;
  pepReaderOps({ args, userId, bookId });
  saveBookData(bookId, null);
};

/**
 * 暂停下载
 * @param {*} param0
 */
const bookDownloadCancel = async ({ userId, bookId }) => {
  const args = `${taskId} bookDownloadCancel ${userId} ${bookId}`;
  pepReaderOps({ args, userId, bookId });
  saveBookData(bookId, null);
  onEvent('cancel', { userId, bookId, status: 1 });
};

/**
 * 阅读器操作
 * @param {*} param0
 */
const pepReaderOps = async ({ args, userId, bookId, bookExe = '' }) => {
  return new Promise((resole) => {
    const spawnObj = spawn(`"${exePath}"`, [args], { detached: false, shell: true, cwd: exeDir });
    spawnObj.stdout.on('data', function (data) {
      data = data.toString().replace('\r\n', '');
      if (data.indexOf('没有下载权限') >= 0) {
        const msg = data.split(',');
        const id = msg[0].split(':')[1] || '';
        const message = msg[1].split(':')[1];
        console.log('error', data);
        onEvent('error', { userId, bookId: id, message, status: 0 });
        resole();
      }
      if (data.indexOf('DownloadProgress') >= 0) {
        let type = '';
        const msg = data.split(',');
        const id = msg[0].split(':')[1] || '';
        const md5 = bookMd5s[id] || '';
        const progress = parseInt(msg[1].split(':')[1]) || 0;
        const downType = parseInt(msg[2].split(':')[1]) || 0;
        const isDownloadResource = parseInt(msg[3].split(':')[1]) || 0;
        const res = { 1: [0, 0, 0], 2: [0, 0, progress] };
        if (data.indexOf('DownloadProgress:100') >= 0) {
          if (downType === 1) {
            type = 'chapter';
          } else if (downType === 0) {
            type = isDownloadResource === 0 ? 'pdf' : 'all';
          }
          saveBookData(id, { bookMd5: md5, bookExe, date: new Date(), status: 1, downType: type });
          onEvent('complete', { userId, bookId: id, bookMd5: md5, bookExe, status: 1 });
          resole();
        } else {
          onEvent('progress', { userId, bookId: id, bookMd5: md5, bookExe, contentLength: 100, ...res });
        }
      }
      if (data.indexOf('chapter') >= 0) {
        onEvent('chapterGet complete', { userId, bookId, status: 1, data });
        resole();
      }
    });
    spawnObj.on('error', (data) => {
      console.log('error:' + data);
      onEvent('error', { userId, data, status: 0 });
    });
  });
};

export default {
  bookList,
  bookInstall,
  bookOpen,
  bookChaptersGet,
  bookUninstall,
  bookDownloadCancel,
};
